package com.leochan.utils.xml;

import java.io.ByteArrayInputStream;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.util.Log;

public class SaxUtils {

	public static <T extends IFeed> T getFeed(String str, boolean isURL,
			FeedHandler<T> handler) {
		if (handler == null) {
			return null;
		}
		try {

			// create the factory
			SAXParserFactory factory = SAXParserFactory.newInstance();
			// create a parser
			SAXParser parser = factory.newSAXParser();

			// create the reader (scanner)
			XMLReader xmlreader = parser.getXMLReader();
			// instantiate our handler
			// assign our handler
			xmlreader.setContentHandler(handler);
			xmlreader.setDTDHandler(handler);
			xmlreader.setErrorHandler(handler);
			xmlreader.setEntityResolver(handler);
			// get our data through the url class

			// setup the url
			InputSource is = null;
			if (isURL) {
				URL url = new URL(str);
				is = new InputSource(url.openStream());
			} else {
				is = new InputSource(new ByteArrayInputStream(str.getBytes()));
			}
			xmlreader.parse(is);
			// perform the synchronous parse
			// get the results - should be a fully populated RSSFeed instance,
			// or null on error
			return handler.getFeed();
		} catch (Exception ee) {
			// if you have a problem, simply return null
			Log.e("test", "getFeed Exception");
			return null;
		}
	}
}
